package com.yulang.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yulang.web.mapper.SysRoleMapper;
import com.yulang.web.pojo.SysPermission;
import com.yulang.web.pojo.SysRole;
import com.yulang.web.pojo.SysRolePermission;
import com.yulang.web.service.SysPermissionService;
import com.yulang.web.service.SysRolePermissionService;
import com.yulang.web.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @Autowired
    private SysRoleMapper mapper;

    @Override
    public SysRole findById(String roleId) {
        SysRole sysRole = this.getById(roleId);
        List<SysPermission> permission = sysPermissionService.findPermissionByRoleId(roleId);
        sysRole.setPerList(permission);
        return sysRole;
    }

    @Transactional
    @Override
    public void saveOrUpdateRolePermission(SysRole sysRole) {
        QueryWrapper<SysRolePermission> remove = new QueryWrapper<>();
        remove.lambda().eq(SysRolePermission::getRoleId,sysRole.getId());
        sysRolePermissionService.remove(remove);
        this.saveOrUpdate(sysRole);
        List<SysRolePermission> list = new ArrayList<>();
        sysRole.getPerIds().forEach(item->{
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(sysRole.getId());
            sysRolePermission.setPermissionId(item);
            list.add(sysRolePermission);
        });
        sysRolePermissionService.saveBatch(list);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        this.removeById(id);
        QueryWrapper<SysRolePermission> remove = new QueryWrapper<>();
        remove.lambda().eq(SysRolePermission::getRoleId,id);
        sysRolePermissionService.remove(remove);
    }

    @Override
    public List<SysRole> findRoleByUserId(String userId) {
        return mapper.findRoleByUserId(userId);
    }
}
